package com.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述:
 *
 * @author luzhongfu
 * Created by lucky on 2020-06-01 1:24 PM
 */
public class MyLock {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Lock lock = new ReentrantLock();
        User user = new User(lock, 100);
        for (int i=1;i<=10;i++){
            executorService.execute(new MyThreadLock(user,i));
        }
        executorService.shutdown();
    }

    static class User {
        private Lock lock;

        private int num;

        public User(Lock lock, int num) {
            this.lock = lock;
            this.num = num;
        }

        public void pop(int item){
            lock.lock();
            num = num - item;
            System.out.println("现在的num="+num);
            lock.unlock();
        }
    }

    static class MyThreadLock implements Runnable{
        private User user;

        private int item;

        public MyThreadLock(User user, int item) {
            this.user = user;
            this.item = item;
        }

        @Override
        public void run() {
            user.pop(item);
        }
    }
}
